<template>
  <div>
    <el-form
      ref="form"
      :model="form"
      label-width="100px"
      class="formWrapper"
      labelPosition="left"
    >
      <el-form-item label="Logo">
        <img-upload v-model="form.logo" :previewStyle="{width: '80px', height: '80px'}"></img-upload>
      </el-form-item>
      <el-form-item label="官网图片">
        <el-button type="primary" @click="showDialog">素材库</el-button>
        <div :class="$style.preview">
          <img :src="item" class="img-block" v-for="item in pictures">
        </div>
      </el-form-item>
      <el-form-item label="版权信息">
        <el-input v-model="form.copyright" placeholder="请输入版权信息"></el-input>
      </el-form-item>
      <el-form-item label="备案信息">
        <el-input v-model="form.icp" placeholder="请输入备案信息"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="large" type="primary" @click="onSubmit">保 存</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="官网图片" size="large" :visible.sync="dialogVisible">
      <gallery v-model="pictures" :openInDialog="true"></gallery>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideDialog">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as apis from 'services/officialSite'
import { ImgUpload } from 'components'
import Gallery from './Gallery'

export default {
  name: 'OfficialSite',
  components: {
    Gallery,
    ImgUpload,
  },
  data() {
    return {
      dialogVisible: false,
      pictures: [],
      form: {
        logo: '',
        copyright: '',
        icp: '',
      },
    }
  },
  created() {
    apis.getSite()
      .then((data) => {
        /* eslint-disable guard-for-in */
        for (const prop in data) {
          this.$set(this.form, prop, data[prop])
        }
        this.pictures = data.picture ? data.picture.split('|') : []
        this.id = data.id
      })
  },
  methods: {
    showDialog() {
      this.dialogVisible = true
    },
    hideDialog() {
      this.dialogVisible = false
    },
    confirm() {
      this.hideDialog()
    },
    onSubmit() {
      const payload = {
        ...this.form,
        picture: this.pictures.join('|'),
      }
      if (this.id) {
        payload.id = this.id
      }
      apis.saveSite(payload)
        .then(() => {
          this.$message({
            type: 'success',
            message: '保存成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'error',
            message: '保存失败',
          })
        })
    },
  },
}
</script>

<style module>
.preview {
  margin: 12px 0;
  max-width: 600px;
}

.preview img {
  margin-top: 12px;
}
</style>
